package com.heima.wemedia.filter;

import com.alibaba.fastjson.JSON;
import com.heima.wemedia.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
全局过滤器，过滤前端传过来的请求，获取token,解析将用户id在复制到请求头中，有些请求是不用拦截的设置成白名单直接放行即可，如登录，注册。
白名单放在静态代码块就可以了
* */
@Component//加入到ioc容器中
@Slf4j
@Order(0) //执行优先级，越小前置越先执行
public class AuthorizeFilter implements GlobalFilter {
    private static List<String> urlList = new ArrayList<>();
    static {
           urlList.add("/login/in");
           urlList.add("/v2/api-docs");//api文档
    }
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
       //1.获取请求，响应
        ServerHttpRequest request = exchange.getRequest();

        //2.判断请求路径是否是白名单路径，是就直接放行
        String resUrl = request.getURI().getPath();//将路径转换为字符串方便对比
        for (String url : urlList) {
            if (resUrl.contains(url)){
                return chain.filter(exchange);
            }
        }
        //3.获取token
        String jwttoken = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(jwttoken)){
            return writeMessage(exchange, "没有token");
        }
        //4.获取token中的负载
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(jwttoken);
            //5.判断token中数据是否有效
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i <1 ) {//
                //6.解析令牌,将id重新存储在请求头上
                Integer id = claimsBody.get("id", Integer.class);
                request.mutate().header("userId", String.valueOf(id));
                exchange.mutate().request(request);
                return chain.filter(exchange);
            }

        }catch (Exception e){
            e.printStackTrace();

        }
        //token无效，终止请求
        return writeMessage(exchange, "token失效");
    }

//返回错误信息
    private Mono<Void> writeMessage(ServerWebExchange exchange, String message) {
        Map<String,Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("errorMessage",message);
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //设置返回数据
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(map));
        //响应数据回浏览器
        return response.writeWith(Flux.just(buffer));
    }
}
